package com.page.common.util;

import java.util.StringTokenizer;
import java.util.Vector;

import com.page.common.vo.TokenVO;

/**
 * 字符串管理集合对象
 * 
 * @Package com.page.common.util
 * @File Tokens.java
 * @author shuxin.zheng@net263.com
 * @date 2014-9-17 下午01:42:05
 */
public class Tokens {

    Vector<TokenVO> tokens = new Vector<TokenVO>();

    public Tokens(String buf) {
        buf.trim();
        StringTokenizer sk = new StringTokenizer(buf, ",;");
        while (sk.hasMoreTokens()) {
            String str = sk.nextToken();
            String[] nv = str.split(":");
            if (nv.length != 2)
                continue;
            TokenVO tokenVO = new TokenVO(nv[0], nv[1]);
            tokens.add(tokenVO);
        }
    }

    public Vector<TokenVO> getTokens() {
        return tokens;
    }

    public String getString(String name) {
        for (TokenVO t : tokens) {
            if (t.size() >= 2 && name.equalsIgnoreCase(t.getFirst()))
                return t.get(1);
        }

        return null;
    }

    public int getInt(String name, int defaultValue) {
        String value = getString(name);
        if (value == null)
            return defaultValue;
        return Integer.parseInt(value);
    }

    public Long getLong(String name, Long defaultValue) {
        String value = getString(name);
        if (value == null)
            return defaultValue;
        return Long.parseLong(value);
    }

    // ///////////////////////////////////////////////////////////////////////

    public static void main(String[] args) {
        String buf = "192.168.188.1:8080; 192.168.188.2:8080;, 192.168.188.3:8080, 192.168.188.4:8080";
        Tokens tokens = new Tokens(buf);
        Vector<TokenVO> vector = tokens.getTokens();
        for (TokenVO tokenVO : vector) {
            Vector<String> strings = tokenVO.getVector();
            for (String string : strings) {
                System.out.print("[" + string + "]");
            }
            System.out.println("");
        }
    }

}
